<template>
  <div class="profile-container">
    <a-card title="个人信息" class="profile-card">
      <a-row :gutter="[24, 24]">
        <a-col :span="8">
          <div class="avatar-section">
            <a-avatar :size="120" :src="userInfo.avatar" class="profile-avatar">
              {{ userInfo.name?.charAt(0) || '仙' }}
            </a-avatar>
            <a-button type="primary" class="upload-btn" @click="handleAvatarUpload">
              <UploadOutlined />
              更换头像
            </a-button>
          </div>
        </a-col>
        <a-col :span="16">
          <a-form ref="formRef" :model="formData" :rules="rules" layout="vertical" @finish="handleSubmit">
            <a-row :gutter="16">
              <a-col :span="12">
                <a-form-item label="姓名" name="name">
                  <a-input v-model:value="formData.name" placeholder="请输入姓名" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="职位" name="position">
                  <a-input v-model:value="formData.position" placeholder="请输入职位" />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="16">
              <a-col :span="12">
                <a-form-item label="部门" name="department">
                  <a-select v-model:value="formData.department" placeholder="请选择部门">
                    <a-select-option value="archives">生灵档案司</a-select-option>
                    <a-select-option value="lifedeath">生死司</a-select-option>
                    <a-select-option value="karma">因果司</a-select-option>
                    <a-select-option value="reincarnation">轮回司</a-select-option>
                    <a-select-option value="judgment">审判司</a-select-option>
                    <a-select-option value="salvation">超度司</a-select-option>
                    <a-select-option value="management">机构管理司</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="等级" name="level">
                  <a-select v-model:value="formData.level" placeholder="请选择等级">
                    <a-select-option value="1">一级仙官</a-select-option>
                    <a-select-option value="2">二级仙官</a-select-option>
                    <a-select-option value="3">三级仙官</a-select-option>
                    <a-select-option value="4">四级仙官</a-select-option>
                    <a-select-option value="5">五级仙官</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="16">
              <a-col :span="12">
                <a-form-item label="联系方式" name="contact">
                  <a-input v-model:value="formData.contact" placeholder="请输入联系方式" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="入职时间" name="joinDate">
                  <a-date-picker v-model:value="formData.joinDate" placeholder="请选择入职时间" style="width: 100%" />
                </a-form-item>
              </a-col>
            </a-row>
            <a-form-item label="个人简介" name="description">
              <a-textarea v-model:value="formData.description" placeholder="请输入个人简介" :rows="4" />
            </a-form-item>
            <a-form-item>
              <a-space>
                <a-button type="primary" html-type="submit" :loading="loading"> 保存修改 </a-button>
                <a-button @click="handleReset">重置</a-button>
              </a-space>
            </a-form-item>
          </a-form>
        </a-col>
      </a-row>
    </a-card>

    <!-- 修改密码卡片 -->
    <a-card title="修改密码" class="password-card">
      <a-form ref="passwordFormRef" :model="passwordData" :rules="passwordRules" layout="vertical" @finish="handlePasswordChange">
        <a-row :gutter="16">
          <a-col :span="8">
            <a-form-item label="当前密码" name="currentPassword">
              <a-input-password v-model:value="passwordData.currentPassword" placeholder="请输入当前密码" />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="新密码" name="newPassword">
              <a-input-password v-model:value="passwordData.newPassword" placeholder="请输入新密码" />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="确认新密码" name="confirmPassword">
              <a-input-password v-model:value="passwordData.confirmPassword" placeholder="请再次输入新密码" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-form-item>
          <a-button type="primary" html-type="submit" :loading="passwordLoading"> 修改密码 </a-button>
        </a-form-item>
      </a-form>
    </a-card>

    <!-- 登录记录卡片 -->
    <a-card title="最近登录记录" class="login-record-card">
      <a-table :columns="loginColumns" :data-source="loginRecords" :pagination="false" size="small" />
    </a-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { UploadOutlined } from '@ant-design/icons-vue'
import { useUserStore } from '@/stores'
import dayjs from 'dayjs'

// 状态管理
const userStore = useUserStore()

// 响应式数据
const loading = ref(false)
const passwordLoading = ref(false)
const formRef = ref()
const passwordFormRef = ref()

// 表单数据
const formData = reactive({
  name: '',
  position: '',
  department: '',
  level: '',
  contact: '',
  joinDate: null,
  description: ''
})

// 密码修改数据
const passwordData = reactive({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 用户信息
const userInfo = computed(() => userStore.userInfo)

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  position: [{ required: true, message: '请输入职位', trigger: 'blur' }],
  department: [{ required: true, message: '请选择部门', trigger: 'change' }],
  level: [{ required: true, message: '请选择等级', trigger: 'change' }]
}

// 密码验证规则
const passwordRules = {
  currentPassword: [{ required: true, message: '请输入当前密码', trigger: 'blur' }],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码至少6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value) => {
        if (value !== passwordData.newPassword) {
          return Promise.reject('两次输入的密码不一致')
        }
        return Promise.resolve()
      },
      trigger: 'blur'
    }
  ]
}

// 登录记录表格列
const loginColumns = [
  {
    title: '登录时间',
    dataIndex: 'loginTime',
    key: 'loginTime'
  },
  {
    title: 'IP地址',
    dataIndex: 'ipAddress',
    key: 'ipAddress'
  },
  {
    title: '登录设备',
    dataIndex: 'device',
    key: 'device'
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status'
  }
]

// 模拟登录记录数据
const loginRecords = ref([
  {
    key: '1',
    loginTime: '2024-01-15 09:30:00',
    ipAddress: '192.168.1.100',
    device: 'Windows Chrome',
    status: '成功'
  },
  {
    key: '2',
    loginTime: '2024-01-14 14:20:00',
    ipAddress: '192.168.1.100',
    device: 'Windows Chrome',
    status: '成功'
  },
  {
    key: '3',
    loginTime: '2024-01-13 08:15:00',
    ipAddress: '192.168.1.105',
    device: 'MacOS Safari',
    status: '成功'
  }
])

// 方法
const handleSubmit = async (values) => {
  loading.value = true
  try {
    // 模拟保存用户信息
    await new Promise((resolve) => setTimeout(resolve, 1000))

    // 更新用户信息
    userStore.updateUserInfo(values)

    message.success('个人信息更新成功')
  } catch (error) {
    message.error('保存失败，请重试')
  } finally {
    loading.value = false
  }
}

const handleReset = () => {
  initFormData()
}

const handleAvatarUpload = () => {
  // 这里可以实现头像上传功能
  message.info('头像上传功能开发中...')
}

const handlePasswordChange = async (values) => {
  passwordLoading.value = true
  try {
    // 模拟修改密码
    await new Promise((resolve) => setTimeout(resolve, 1000))

    message.success('密码修改成功')

    // 重置密码表单
    passwordFormRef.value.resetFields()
  } catch (error) {
    message.error('密码修改失败，请重试')
  } finally {
    passwordLoading.value = false
  }
}

const initFormData = () => {
  // 初始化表单数据
  formData.name = userInfo.value.name || ''
  formData.position = userInfo.value.position || ''
  formData.department = userInfo.value.department || ''
  formData.level = userInfo.value.level || ''
  formData.contact = userInfo.value.contact || ''
  formData.joinDate = userInfo.value.joinDate ? dayjs(userInfo.value.joinDate) : null
  formData.description = userInfo.value.description || ''
}

// 生命周期
onMounted(() => {
  initFormData()
})
</script>

<style lang="scss" scoped>
.profile-container {
  .profile-card,
  .password-card,
  .login-record-card {
    margin-bottom: $spacing-lg;
  }

  .avatar-section {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: $spacing-md;

    .profile-avatar {
      border: 2px solid $border-color;
      font-size: 48px;
    }

    .upload-btn {
      width: 120px;
    }
  }

  :deep(.ant-card-head-title) {
    font-size: $font-size-lg;
    font-weight: bold;
  }

  :deep(.ant-form-item-label > label) {
    font-weight: 500;
  }
}
</style>
